package berlinatyourfingertips.ua.apis;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import processing.xml.XMLElement;

import berlinatyourfingertips.ua.UAInterface;
import berlinatyourfingertips.ua.UAResult;
import berlinatyourfingertips.ua.UAResultSet;

public class UATwitter implements UAInterface {	
	
	public UAResultSet getAllAtPosition(float latitude, float longitude) {
		return getJSON("http://search.twitter.com/search.json?geocode="+latitude+"%2C"+longitude+"%2C100km&rpp=100");
	}

	public UAResultSet getPosition(int maxResultLength, float latitude,	float longitude) {
		// TODO Find out hwo to do this and ... implement ;)
		return null;
	}

	public UAResultSet getAll() {
		return getXML("http://twitter.com/statuses/public_timeline.xml");
	}

	private UAResultSet getJSON(String url) {
		//System.out.println("Twitter: request startet.");
		
		UAResultSet result = new UAResultSet();
		
		String httpResult = UAHttp.get(url);
		
		//System.out.println(httpResult);
		
		//System.out.println("Twitter: processing result.");
			
		try {
			JSONObject jos = new JSONObject(new JSONTokener(httpResult));
			JSONArray  ja = jos.getJSONArray("results");
			for(int i = 0; i < ja.length(); i++) {
//				float longi = (float)ja.getJSONObject(i).getDouble("longitude");
//				System.out.println("Panoramio: adding "+lati+"/"+longi);
				UAResult r = new UAResult(ja.getJSONObject(i).getString("text"));
				r.setId(Integer.parseInt(ja.getJSONObject(i).getString("id")));
				result.add(r);
			}
		} catch (JSONException e) {			
			e.printStackTrace();
		}
		
		return result;
	}	
	
	private UAResultSet getXML(String url) {
		//System.out.println("Twitter: request startet.");
		
		UAResultSet result = new UAResultSet();
		
		String httpResult = UAHttp.get(url);
		
		//System.out.println(httpResult);
		
		//System.out.println("Twitter: processing result.");
			
		XMLElement xml = new XMLElement(httpResult);
		  int numStatuses = xml.getChildCount();
		  for (int i = 0; i < numStatuses; i++) {
		    XMLElement kid = xml.getChild(i);
		    kid.getChildCount();
		   // System.out.println("Twitter: adding id: "+kid.getChild("id").getContent());
		    UAResult uar = new UAResult(kid.getChild("text").getContent());
		    uar.setId(Integer.parseInt(kid.getChild("id").getContent()));
		    result.add(uar);
		  }		
		
		
		return result;
	}

}
